﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace TaDMS.Models
{
    public class ReportRepository : Repository<Report>
    {
        public new string ErrorMessage { get; set; }

        public ReportRepository(DbContext model) : base(model)
        {
        }

        public IEnumerable<Report> ViewReport(DateTime? startDate, DateTime? endDate, string title, int currentUserId, int isAll)
        {
            var filterExpressions = new List<Expression<Func<Report, bool>>>();
            if (title != null && !String.IsNullOrWhiteSpace(title))
            {
                Expression<Func<Report, bool>> expression = report => report.ReportTitle.ToUpper().Contains(title.ToUpper());
                filterExpressions.Add(expression);
            }
            if (startDate != null && endDate != null)
            {
                Expression<Func<Report, bool>> expression = report => report.CreateDate <= endDate && report.CreateDate >= startDate;
                filterExpressions.Add(expression);
            }
            
            //Get user
            using (var db = new TaDMS())
            {
                var userIds = db.sp_Task_GetResource(currentUserId, isAll).Select(v => v.EmployeeId as int?).ToList();
                if (userIds.Any())
                {
                    Expression<Func<Report, bool>> expression = report => userIds.Contains(report.EmployeeId);
                    filterExpressions.Add(expression);
                }
                else
                {
                    this.ErrorMessage = "Employee is empty";
                    return null;
                }
            }


            int? total;
            var reports = base.GetData(total: out total, orderBy: order => order.OrderBy(v => v.CreateDate), multiFilter: filterExpressions, includeProperties: "Employee" );

            if (!String.IsNullOrEmpty(base.ErrorMessage))
            {
                this.ErrorMessage = base.ErrorMessage;
                return null;
            }
            else
            {
                return reports;
            }
        }
    }
}